package com.deyou.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.deyou.AppManager;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.CityBean;
import com.deyou.model.SimpleResponse;
import com.deyou.model.UserInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.deyou.widget.CircleImageView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.album.Album;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UserInfoActivity extends BaseActivity {

    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.user_pic)
    CircleImageView userPic;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.nick_name_layout)
    RelativeLayout nickNameLayout;
    @BindView(R.id.ic_man_sex)
    ImageView icManSex;
    @BindView(R.id.man_sex_layout)
    LinearLayout manSexLayout;
    @BindView(R.id.ic_female_sex)
    ImageView icFemaleSex;
    @BindView(R.id.female_sex_layout)
    LinearLayout femaleSexLayout;
    @BindView(R.id.user_sex_layout)
    RelativeLayout userSexLayout;
    @BindView(R.id.tv_mail)
    TextView tvMail;
    @BindView(R.id.mail_layout)
    RelativeLayout mailLayout;
    @BindView(R.id.tv_region)
    TextView tvRegion;
    @BindView(R.id.region_layout)
    RelativeLayout regionLayout;
    @BindView(R.id.tv_user_intro)
    TextView tvUserIntro;
    @BindView(R.id.user_intro_layout)
    RelativeLayout userIntroLayout;
    @BindView(R.id.tv_user_hobby)
    TextView tvUserHobby;
    @BindView(R.id.user_hobby_layout)
    RelativeLayout userHobbyLayout;

    private int userSexValue = 1;
    private ArrayList<String> mImageList = new ArrayList<>();
    private String uploadImgUrl = "";
    private String userRegion = "";
    private List<CityBean> countryList = new ArrayList<>();
    private List<List<CityBean>> provinceList = new ArrayList<>();
    private List<List<List<CityBean>>> cityList = new ArrayList<>();


    private List<String> countryStrList = new ArrayList<>();
    private List<List<String>> provinceStrList = new ArrayList<>();
    private List<List<List<String>>> cityStrList = new ArrayList<>();


    private Thread thread;
    private boolean isLoaded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
        initView();
        initUserInfo();

        if (thread == null) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    initOptionData();
                }
            });
            thread.start();
        }
    }

    private void initView() {
        tvMidTitle.setText("资料编辑");
        tvRight.setText("保存");
        tvRight.setVisibility(View.VISIBLE);
        ivRight.setVisibility(View.GONE);
    }

    private void initUserInfo() {
        UserInfoBean user = UserInfoBean.where("userId = ?", SPUtils.getStringByKey(this, Constants.UserId)).findFirst(UserInfoBean.class);
        if (null != user) {
            if (!TextUtils.isEmpty(user.userPic))
                new GlideImageLoader().displayImage(this, user.userPic, userPic);
            else
                new GlideImageLoader().displayImage(this, R.drawable.ic_default_avatar2, userPic);
            if (user.userSex == 1) {
                icManSex.setImageResource(R.drawable.ic_choosed_sex);
                icFemaleSex.setImageResource(R.drawable.ic_unchoos_sex);
            } else {
                icManSex.setImageResource(R.drawable.ic_unchoos_sex);
                icFemaleSex.setImageResource(R.drawable.ic_choosed_sex);
            }
            tvNickName.setText(user.userNickname);
            tvRegion.setText(user.userRegionName);
            tvUserIntro.setText(user.userIntroduction);
            tvUserHobby.setText(user.userHobby);
        }
    }

    private void initOptionData() {

        countryList = DataSupport.where("pid = ?", "1000000000").find(CityBean.class);
        if (null != countryList && countryList.size() > 0) {
            for (int i = 0; i < countryList.size(); i++) { // 遍历国家
                String countryStr = countryList.get(i).regionName;
                countryStrList.add(countryStr);
                List<String> tempProvinceStrList = new ArrayList<>();
                List<CityBean> tempProvinceList = DataSupport.where("pid = ?", countryList.get(i).regionId).find(CityBean.class);
                if (null != tempProvinceList && tempProvinceList.size() > 0) {
                    List<List<String>> tempCityStrList = new ArrayList<>();
                    List<List<CityBean>> tempCityList = new ArrayList<>();
                    for (int j = 0; j < tempProvinceList.size(); j++) { // 遍历省
                        String provinceStr = tempProvinceList.get(j).regionName;
                        tempProvinceStrList.add(provinceStr);
                        List<String> tempCityStr = new ArrayList<>();
                        List<CityBean> tempCity = DataSupport.where("pid = ?", tempProvinceList.get(j).regionId).find(CityBean.class);
                        if (null != tempCity && tempCity.size() > 0) {
                            tempCityList.add(tempCity);
                            for (int m = 0; m < tempCity.size(); m++) {
                                if (null != tempCity.get(m)){
                                    String cityStr = tempCity.get(m).regionName;
                                    tempCityStr.add(cityStr);
                                }
                            }
                        }
                        tempCityStrList.add(tempCityStr);
                    }
                    cityList.add(tempCityList);
                    cityStrList.add(tempCityStrList);
                } else {
                    tempProvinceList.add(new CityBean());
                    tempProvinceStrList.add("");
                }
                provinceList.add(tempProvinceList);
                provinceStrList.add(tempProvinceStrList);
            }
        }

        isLoaded = true;
    }

    @OnClick({R.id.iv_left_back, R.id.tv_right, R.id.user_pic, R.id.nick_name_layout, R.id.man_sex_layout,
            R.id.female_sex_layout, R.id.mail_layout, R.id.region_layout, R.id.user_intro_layout, R.id.user_hobby_layout})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.tv_right:
                if (null != mImageList && mImageList.size() > 0) {
                    uploadUserImg();
                } else {
                    updateUserInfo();
                }
                break;
            case R.id.user_pic:
                callAlbum();
                break;
            case R.id.nick_name_layout:
                bundle.putInt("inputType", Constants.EditInputTypeNick);
                AndroidUtils.startNextActivityForResult(UserInfoActivity.this, InfoEditActity.class, bundle, Constants.EditInputTypeNick);
                break;
            case R.id.man_sex_layout:
                icManSex.setImageResource(R.drawable.ic_choosed_sex);
                icFemaleSex.setImageResource(R.drawable.ic_unchoos_sex);
                userSexValue = 1;
                break;
            case R.id.female_sex_layout:
                icManSex.setImageResource(R.drawable.ic_unchoos_sex);
                icFemaleSex.setImageResource(R.drawable.ic_choosed_sex);
                userSexValue = 0;
                break;
            case R.id.mail_layout:
                break;
            case R.id.region_layout:
                if (isLoaded) {
                    ShowPickerView();
                } else {
                    showToast("地区数据正在加载中，请稍后...");
                }
                break;
            case R.id.user_intro_layout:
                bundle.putInt("inputType", Constants.EditInputTypeIntro);
                AndroidUtils.startNextActivityForResult(UserInfoActivity.this, InfoEditActity.class, bundle, Constants.EditInputTypeIntro);
                break;
            case R.id.user_hobby_layout:
                bundle.putInt("inputType", Constants.EditInputTypeHobby);
                AndroidUtils.startNextActivityForResult(UserInfoActivity.this, InfoEditActity.class, bundle, Constants.EditInputTypeHobby);
                break;
        }
    }

    private void ShowPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String countryStr = "";
                String countryCode = "";
                String provinceStr = "";
                String provinceCode = "";
                String cityStr = "";
                String cityCode = "";
                if (null != countryList
                        && countryList.size() > options1
                        && null != countryList.get(options1)){
                    countryStr = countryList.get(options1).regionName + " ";
                    countryCode = countryList.get(options1).regionId + " ";
                }
                if (null != provinceList && provinceList.size() > options1
                        && null != provinceList.get(options1)
                        && provinceList.get(options1).size() >options2
                        && null != provinceList.get(options1).get(options2)){
                    provinceStr = provinceList.get(options1).get(options2).regionName + " ";
                    provinceCode = provinceList.get(options1).get(options2).regionId + " ";
                }
                if (null != cityList && cityList.size() > options1
                        && null != cityList.get(options1)
                        && cityList.get(options1).size() > options2
                        && null != cityList.get(options1).get(options2)
                        && cityList.get(options1).get(options2).size() > options3
                        && null != cityList.get(options1).get(options2).get(options3)){
                    cityStr = cityList.get(options1).get(options2).get(options3).regionName;
                    cityCode = cityList.get(options1).get(options2).get(options3).regionId;
                }
                String tx = countryStr + provinceStr + cityStr;
                tvRegion.setText(tx);
                userRegion = !TextUtils.isEmpty(cityCode) ? cityCode : !TextUtils.isEmpty(provinceCode) ? provinceCode : !TextUtils.isEmpty(countryCode) ? countryCode : "";
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(getResources().getColor(R.color.color_E5E5E5))
                .setTextColorCenter(getResources().getColor(R.color.color_272424)) //设置选中项文字颜色
                .setSubmitColor(getResources().getColor(R.color.color_FF832D))
                .setCancelColor(getResources().getColor(R.color.color_959090))
                .setTitleColor(getResources().getColor(R.color.color_272424))//标题文字颜色
                .setTitleSize(14)//标题文字大小
                .setSubCalSize(14)//确定和取消文字大小
                .setContentTextSize(16)
                .setOutSideCancelable(false)// default is true
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(countryStrList, provinceStrList, cityStrList);//三级选择器
        pvOptions.show();
    }

    private void callAlbum() {
        Album.albumRadio(this)
                .toolBarColor(getResources().getColor(R.color.color_FF832D)) // Toolbar 颜色，默认蓝色。
                .statusBarColor(getResources().getColor(R.color.color_FF832D)) // StatusBar 颜色，默认蓝色。
//                .navigationBarColor(navigationBarColor) // NavigationBar 颜色，默认黑色，建议使用默认。
                .title("图库") // 配置title。
//                .selectCount(1) // 最多选择几张图片。
                .columnCount(3) // 相册展示列数，默认是2列。
                .camera(true) // 是否有拍照功能。
//                .checkedList(mImageList) // 已经选择过得图片，相册会自动选中选过的图片，并计数。
                .start(999);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 999:
                if (resultCode == RESULT_OK) { // Successfully.
                    mImageList = Album.parseResult(data);
                    if (null != mImageList && mImageList.size() > 0) {
                        new GlideImageLoader().displayImage(this, mImageList.get(0), userPic);
                    } else {
                        new GlideImageLoader().displayImage(this, R.drawable.ic_default_avatar2, userPic);
                    }
                } else if (resultCode == RESULT_CANCELED) { // User canceled.
                    // 用户取消了操作。
                }
                break;
            case Constants.EditInputTypeNick:
                if (null != data && null != data.getExtras() && resultCode == RESULT_OK)
                    tvNickName.setText(data.getExtras().getString("inputValue"));
                break;
            case Constants.EditInputTypeIntro:
                if (null != data && null != data.getExtras() && resultCode == RESULT_OK)
                    tvUserIntro.setText(data.getExtras().getString("inputValue"));
                break;
            case Constants.EditInputTypeHobby:
                if (null != data && null != data.getExtras() && resultCode == RESULT_OK)
                    tvUserHobby.setText(data.getExtras().getString("inputValue"));
                break;
        }
    }

    private void uploadUserImg() {
        Observable.create(new ObservableOnSubscribe<Progress>() {
            @Override
            public void subscribe(@NonNull final ObservableEmitter<Progress> e) throws Exception {
                OkGo.<String>post(Urls.uploadSingleImg)//
                        .tag(this)//
//                        .params("file",new File(imageItems.get(0).path))
                        //.params("file2",new File("文件路径"))
                        .params("type", "1")
                        .params("file", new File(mImageList.get(0)))//
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                e.onComplete();
                                SimpleResponse resp = new Gson().fromJson(response.body(), SimpleResponse.class);
                                uploadImgUrl = resp.data;
                            }

                            @Override
                            public void onError(Response<String> response) {
                                e.onError(response.getException());
                            }

                            @Override
                            public void uploadProgress(Progress progress) {
                                e.onNext(progress);
                            }
                        });
            }
        })//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())//
                .subscribe(new Observer<Progress>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(@NonNull Progress progress) {
                        showLoading("图像上传中" + (int) (progress.fraction * 100) + "%");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                        updateUserInfo();
                    }
                });
    }

    private void updateUserInfo() {
        final Bundle b = new Bundle();
        final Message msg = new Message();
        JSONObject object = new JSONObject();
        try {
            object.put("userPic", uploadImgUrl);
            object.put("userNickname", tvNickName.getText().toString().trim());
            object.put("userSex", userSexValue);
            object.put("userRegion", userRegion);
            object.put("userIntroduction", tvUserIntro.getText().toString().trim());
            object.put("userHobby", tvUserHobby.getText().toString().trim());
            object.put("userId", SPUtils.getStringByKey(this, Constants.UserId));
            String paramJson = object.toString();
            Logger.i(Logger.LOGTAG + "编辑用户资料", paramJson);
            ServerApi.getString(Urls.updateUserInfo, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("用户数据上传中...");
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull String s) {
                            SimpleResponse resp = new Gson().fromJson(s, SimpleResponse.class);
                            if (null != resp) {
                                b.putString("errMsg", resp.msg);
                                if (resp.code == 1) {
                                    b.putInt("code", 1);
                                } else {
                                    b.putInt("code", 2);
                                }
                                msg.setData(b);
                                handler.sendMessage(msg);
                            } else {
                                b.putInt("code", 3);
                                msg.setData(b);
                                handler.sendMessage(msg);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            b.putInt("code", 3);
                            msg.setData(b);
                            handler.sendMessage(msg);
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int code = msg.getData().getInt("code");
            switch (code) {
                case 1:
                    showToast("用户信息修改成功");
                    finish();
                    break;
                case 2:
                    String errMsg = msg.getData().getString("errMsg");
                    showToast(errMsg);
                    break;
                case 3:
                    showToast("用户信息修改失败");
                    break;
            }
        }
    };
}
